<script setup lang="ts">
import { reqSpuImageList, reqAllTrademark, reqSaleAttrList, reqBaseSaleAttrList, reqAddOrUpdateSpu } from '@/api/product/spu'
import type { UploadFile, UploadUserFile, UploadProps } from 'element-plus'
import type { ISpuList, ISpu1, ISaleAttr, ISpuSaleAttrData } from '@/api/product/spu/types'
const $emits = defineEmits(['changeScene'])
const backScene = () => {
  $emits('changeScene', 0)
}
const dialogImageUrl = ref('')
const dialogVisible = ref<boolean>(false)
const handleRemove = (file: UploadFile) => {
  console.log(file)
}

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}
const handleUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (['image/jpeg', 'image/png', 'image/gif'].indexOf(rawFile.type) < 0) {
    ElMessage.error('只能上传图像格式文件!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过 2MB!')
    return false
  }
  return true
}

const spuFormData = reactive<ISpuList>({
  category3Id: '',
  spuName: '',
  description: '',
  tmId: '',
  spuImageList: [],
  spuSaleAttrList: []
} as ISpuList)
const allTradeMark = ref<ISpu1[]>([])
const imgList = ref<UploadUserFile[]>([])
const saleAttr = ref<ISpuSaleAttrData[]>([])
const allSaleAttr = ref<ISaleAttr[]>([])
// 计算出当前spu还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  let unSelectArr = allSaleAttr.value.filter((item) => {
    return saleAttr.value.every((item1) => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelectArr
})
// 收集还未选择的ID:属性名
let saleAttrIdAndValueName = ref('')
// 添加销售属性
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  let newSaleAttr: ISpuSaleAttrData = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: []
  }
  saleAttr.value.push(newSaleAttr)
  saleAttrIdAndValueName.value = ''
}

// 子组件初始化数据的方法
const initHasSpuData = async (row: ISpuList) => {
  Object.assign(spuFormData, JSON.parse(JSON.stringify(row)))
  const res1 = await reqAllTrademark()
  if (res1.code == 200) {
    allTradeMark.value = res1.data
  }
  const res2 = await reqSpuImageList(row.id as number)
  if (res2.code == 200) {
    imgList.value = res2.data.map((item) => {
      return { name: item.imgName, url: item.imgUrl }
    })
  }
  const res3 = await reqSaleAttrList(row.id as number)
  if (res3.code == 200) {
    saleAttr.value = res3.data
  }
  const res4 = await reqBaseSaleAttrList()
  if (res4.code == 200) {
    allSaleAttr.value = res4.data
  }
}

const InputRef = ref()

const showInput = (row: ISpuSaleAttrData) => {
  row.flag = true
  row.saleAttrValue = ''
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = (row: ISpuSaleAttrData) => {
  if (row.saleAttrValue) {
    // 重复
    let repeat = row.spuSaleAttrValueList.find((item) => {
      return item.saleAttrValueName === row.saleAttrValue
    })
    if (repeat) {
      ElMessage.error('属性值重复')
      row.flag = false
      row.saleAttrValue = ''
      return
    }

    row.spuSaleAttrValueList.push({ baseSaleAttrId: row.baseSaleAttrId, saleAttrValueName: row.saleAttrValue })
  }
  row.flag = false
  row.saleAttrValue = ''
}
// 保存
const save = async () => {
  // 整理照片墙数据
  spuFormData.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url
    }
  })
  // 整理spu销售属性数据
  spuFormData.spuSaleAttrList = saleAttr.value
  const result = await reqAddOrUpdateSpu(spuFormData)
  if (result.code == 200) {
    ElMessage.success('保存成功')
    $emits('changeScene', 0)
  } else {
    ElMessage.error('保存失败' + result.message)
  }
}
// 添加spu初始化方法
const initAddSpuData = async (cate3Id: number) => {
  Object.assign(spuFormData, {
    category3Id: cate3Id,
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: []
  })
  saleAttr.value = []
  imgList.value = []
  saleAttrIdAndValueName.value = ''
  const res1 = await reqAllTrademark()
  if (res1.code == 200) {
    allTradeMark.value = res1.data
  }

  const res4 = await reqBaseSaleAttrList()
  if (res4.code == 200) {
    allSaleAttr.value = res4.data
  }
}
defineExpose({ initHasSpuData, initAddSpuData })
</script>

<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="spu名称">
        <el-input placeholder="请输入spu名称" style="width: 350px" v-model="spuFormData.spuName" />
      </el-form-item>
      <el-form-item label="spu品牌">
        <el-select v-model="spuFormData.tmId">
          <el-option :label="item.tmName" :value="item.id" v-for="item in allTradeMark" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="spu描述">
        <el-input v-model="spuFormData.description" placeholder="请输品牌描述" type="textarea" style="width: 350px" />
      </el-form-item>
      <el-form-item label="spu照片">
        <el-upload
          v-model:file-list="imgList"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="handleUpload"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%; height: 100%" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="spu销售属性">
        <el-select :placeholder="unSelectSaleAttr.length ? `还未选择${unSelectSaleAttr.length}个` : '无'" v-model="saleAttrIdAndValueName">
          <el-option v-for="item in unSelectSaleAttr" :key="item.id" :label="item.name" :value="`${item.id}:${item.name}`" />
        </el-select>
        <el-button type="primary" icon="Plus" style="margin-left: 10px" :disabled="!saleAttrIdAndValueName" @click="addSaleAttr"
          >添加销售属性</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-table border stripe :data="saleAttr">
          <el-table-column type="index" label="序号" align="center" width="80px"></el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="180px" align="center"></el-table-column>
          <el-table-column label="属性值">
            <template #default="{ row }">
              <el-tag
                v-for="(item, $index) in row.spuSaleAttrValueList"
                :key="item.id"
                style="margin: 5px"
                closable
                class="mx-1"
                @close="row.spuSaleAttrValueList.splice($index, 1)"
              >
                {{ item.saleAttrValueName }}
              </el-tag>

              <el-input
                v-if="row.flag == true"
                ref="InputRef"
                v-model="row.saleAttrValue"
                class="ml-1 w-20"
                size="small"
                @keyup.enter="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
                style="width: 100px"
              />
              <el-button v-else type="primary" size="small" icon="Plus" @click="showInput(row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template #default="{ row, $index }">
              <el-button type="danger" icon="Delete" @click="saleAttr.splice($index, 1)" />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="!saleAttr.length" type="primary" @click="save">保存</el-button>
        <el-button @click="backScene">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped></style>
